package com.xposed.xinhao.hook_pinduoduo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import com.xposed.xinhao.utils.JsonUtils;
import com.xposed.xinhao.utils.LogUtils;

import org.json.JSONArray;
import org.json.JSONException;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * @author lemlin
 * <p>
 * 拼多多商家版
 */
public class PddSellerHook {

    private Context mContext;

    private XC_LoadPackage.LoadPackageParam lpparam;

    public PddSellerHook(XC_LoadPackage.LoadPackageParam lpparam) {
        this.lpparam = lpparam;
    }

    public void hookMethod() {
        XposedHelpers.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                mContext = (Context) param.thisObject;
                LogUtils.e("Activity onCreate：" + mContext.getClass().getName());
            }
        });

        XposedHelpers.findAndHookMethod("com.xunmeng.merchant.ui.MainFrameTabActivity", lpparam.classLoader, "onCreate", Bundle.class, new XC_MethodHook() {
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                callMethodAccount((Context) param.thisObject);
            }
        });
    }

    /**
     * 主动拉起方法获取PASS_ID,SHOP_ID
     */
    public void callMethodAccount(Context context) {
        Class<?> cls = XposedHelpers.findClassIfExists("com.xunmeng.merchant.account.AccountManager", lpparam.classLoader);
        Object account = XposedHelpers.newInstance(cls, new Class[]{Context.class}, context);
        Object object = XposedHelpers.callMethod(account, "i");

        try {
            JSONArray arrays = new JSONArray(JsonUtils.objectToString(object));
            //存在多个用户信息，通过login字段不等于1过滤未登录用户
            for (int i = 0; i < arrays.length(); i++) {
                if (arrays.getJSONObject(i).optInt("login") == 1) {
                    LogUtils.e("mallId:" + arrays.getJSONObject(i).optString("mallId"));
                    LogUtils.e("passId:" + arrays.getJSONObject(i).optString("passId"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtils.e(JsonUtils.objectToString(object));
    }


}
